import { Component, OnInit } from '@angular/core';
import { ApplicationService } from "../../../../service/application.service";
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { Command } from "../../../../shared/toolbar.service";
import { Blade } from "../../../../shared/blade/blade.model";
import { BladeData } from "../../../../shared/blade/blade-data";
import { DialogResult } from "../../../../shared/dialog.service";
import { Observable } from "rxjs/Observable";

import { Role } from "../../../../entity/role.model";
import { RoleEditComponent } from "../role-edit/role-edit.component";
import { RoleService } from "../../../../service/role.service";
import { MenuAccessListComponent } from "../menu-access/menu-access-list/menu-access-list.component";
import { RolePermissionListComponent } from "../role-permission/role-permission-list/role-permission-list.component";
import { MenuShortcutListComponent } from "../menu-shortcut/menu-shortcut-list/menu-shortcut-list.component";
// import { RolePermissionListComponent } from "../permission/permission-list/permission-list.component";
// import { PermissionListComponent } from "../permission/permission-list/permission-list.component";





@Component({
  selector: 'app-role-list',
  templateUrl: './role-list.component.html',
  styleUrls: ['./role-list.component.css']
})
export class RoleListComponent extends BladeContainerBase<Role>{

  /**
   * 角色集合
   * 
   * @type {Role[]}
   * @memberof RoleListComponent
   */
  roles: Role[] = [];
  original: Role[] = [];
  currentRole: Role;

  constructor(
    private application: ApplicationService,
    private roleService: RoleService,
  ) {
    super();
  }

  ngOnInit() {
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),

      new Command("standardCurve", "菜单权限", "fa fa-line-chart", "setofkey:create", blade => this.exeMenuAccess(blade), blade => this.canExeEdit(blade)),
      new Command("stateInfo", "操作权限", "fa fa-circle-o-notch", "setofkey:create", blade => this.showPermission(blade), blade => this.canExeEdit(blade)),
      new Command("faultAlarm", "固定菜单", "fa fa-exclamation-circle", "setofkey:create", blade => this.showMenuShortcut(blade), blade => this.canExeEdit(blade)),
    ];
    super.ngOnInit();
  }



  /**
   * 初始化数据
   * 
   * @returns {(any | Observable<any> | Promise<any>)} 
   * @memberof RoleListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    this.roleService.getRoles()
      .then(res => {
        if (!res) { return false; };
        this.original = [...res];
        this.roles = [...this.original];
        this.currentEntity = this.roles[0];
        this.onSeletedChange(this.currentEntity);
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   * 添加
   * 
   * @param {Blade} blend 
   * @memberof RoleListComponent
   */
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "roleEdit";
    data.title = "新建角色";
    data.isClosingDisabled = false;
    let createKeyBlade = this.bladeService.createBlade(RoleEditComponent, data, true, this.currentEntity);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }
  canExeAdd(blend: Blade): boolean {
    return true;
  }


  /**
   * 编辑
   * 
   * @param {Blade} blend 
   * @memberof RoleListComponent
   */
  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = "roleEdit";
      data.title = this.currentEntity.roleName;
      let editRoleBlade = this.bladeService.createBlade(RoleEditComponent, data, false, this.currentEntity);
      this.currentBlade.bladeService.showBlade(editRoleBlade, this.currentBlade);
    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }



  /**
   * 删除
   * 
   * @param {Blade} blend 
   * @memberof RoleListComponent
   */
  exeDelete(blend: Blade): void {
    let selectedMenus = this.getSelected();
    if (selectedMenus.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;

            this.roleService.batchDelete(selectedMenus.map(o => o.roleId))
              .then(res => {
                if (res.code == '200') {
                  super.refresh(undefined);
                }
                if (res.code == '8001') {
                  this.dialogService
                    .showConfirmationDialog("删除失败", res.message);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }


  /**
   * 单选
   * 
   * @param {HTMLInputElement} event 
   * @param {Role} key 
   * @memberof RoleListComponent
   */
  onItemCheack(event: HTMLInputElement, key: Role) {
    key.isChecked = event.checked;
  }


  /**
   * 全选
   * 
   * @param {HTMLInputElement} event 
   * @memberof RoleListComponent
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.roles.length > 0) {
      for (let i = 0; i < this.roles.length; i++) {
        this.roles[i].isChecked = event.checked;
      }
    }
  }


  /**
   * 获得选中项
   * 
   * @returns {Role[]} 
   * @memberof RoleListComponent
   */
  getSelected(): Role[] {
    if (this.roles.length > 0) {
      let filter = this.roles.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }

  onSeletedChange(selectedRole: Role) {
    if (this.currentBlade.childrenCanDeactivate()) {
      // this.currentBlade.bladeService.closeChildrenBlade;
      // this.currentEntity = selectedRole;    
      this.showMenuAccess(selectedRole, true);
    }
  }

  //显示菜单权限
  showMenuAccess(selectedRole: Role, isShowChild: boolean) {
    if (this.currentEntity != selectedRole || this.bladeService.findBlade("menuAccessList") == undefined) {
      this.currentBlade.bladeService.closeChildrenBlade;
      let data: BladeData = new BladeData();
      data.id = "menuAccessList";
      data.title = selectedRole.roleName;
      data.subtitle = '菜单权限';
      data.isClosingDisabled = false;
      let menuCheckBlade = this.bladeService.createBlade(MenuAccessListComponent, data, false, null, { currentEntity: selectedRole, isShowChild: isShowChild });
      this.bladeService.showBlade(menuCheckBlade, this.currentBlade)
        .then(res => {
          if (res) {
            this.currentEntity = selectedRole;
          }
        });
    }
  }


  exeMenuAccess(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = "menuAccessList";
      data.title = this.currentEntity.roleName;
      data.subtitle = '菜单权限';
      data.isClosingDisabled = false;
      let menuCheckBlade = this.bladeService.createBlade(MenuAccessListComponent, data, false, null, { currentEntity: this.currentEntity, isShowChild: false });
      this.bladeService.showBlade(menuCheckBlade, this.currentBlade);
    }
  }

  //显示操作权限
  showPermission(selectedRole: Role) {
    if (this.currentEntity != undefined) {
      // this.currentBlade.bladeService.closeChildrenBlade;
      let data: BladeData = new BladeData();
      data.id = "PermissionList";
      data.title = this.currentEntity.roleName;
      data.subtitle = '操作权限';
      data.isClosingDisabled = false;
      let menuCheckBlade = this.bladeService.createBlade(RolePermissionListComponent, data, false, null,  { currentEntity: this.currentEntity, isShowChild: false });
      this.bladeService.showBlade(menuCheckBlade, this.currentBlade)
      // .then(res => {
      //   if (res) {
      //     this.currentEntity = selectedRole;
      //   }
      // });
    }
  }


  //显示规定菜单
  showMenuShortcut(selectedRole: Role) {
    if (this.currentEntity != undefined) {
      // this.currentBlade.bladeService.closeChildrenBlade;
      let data: BladeData = new BladeData();
      data.id = "menuShortcutList";
      data.title = this.currentEntity.roleName;
      data.subtitle = '固定菜单';
      data.isClosingDisabled = false;
      let menuCheckBlade = this.bladeService.createBlade(MenuShortcutListComponent, data, false, null, this.currentEntity);
      this.bladeService.showBlade(menuCheckBlade, this.currentBlade)
      // .then(res => {
      //   if (res) {
      //     this.currentEntity = selectedRole;
      //   }
      // });
    }
  }





}



// WEBPACK FOOTER //
// ./src/app/module/admin/role/role-list/role-list.component.ts